package com.example.lzbase;

import android.os.Bundle;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;

import org.greenrobot.eventbus.EventBus;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import utils.ClassUtil;

public abstract class BaseViewModelActivity<VM extends BaseViewModel> extends BaseActivity {
    private CompositeDisposable mCompositeDisposable;
    protected VM viewModel;
    public void addSubscription(Disposable s) {
        if (this.mCompositeDisposable == null) {
            this.mCompositeDisposable = new CompositeDisposable();
        }
        this.mCompositeDisposable.add(s);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


    }

    @Override
    protected void created(@Nullable Bundle savedInstanceState) {
        initViewModel();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


        if (this.mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            // clear 和 dispose的区别是：  disposed = true;
            this.mCompositeDisposable.clear();
        }
    }

    /**
     * 初始化ViewModel
     */
    protected void initViewModel() {
        Class<VM> viewModelClass = ClassUtil.getViewModel(this);
        if (viewModelClass != null) {
            ViewModelProvider viewModelProvider = new  ViewModelProvider(this.getViewModelStore(), new ViewModelProvider.AndroidViewModelFactory(getApplication()));

            this.viewModel= viewModelProvider.get(viewModelClass);
        };


        if(this.viewModel!=null){
            this.viewModel.error.observe(this,error->{

                onError(error);
            });
            this.viewModel.progress.observe(this,show->{
                showLoading(show);
            });
        }



    }

    public  void  onError(Throwable error){
        if( null!=error.getMessage()){
            Toast.makeText(this,error.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }
}
